package com.qf.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.dao.AdminDao;
import com.qf.entity.TbAdmin;
import com.qf.service.AdminService;
import com.qf.utils.ResultMsg;
import com.qf.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 王希卓
 * @Date 2023/7/20 15:23
 * 管理员业务实现
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminDao, TbAdmin> implements AdminService {
    @Autowired(required = false)
    private AdminDao adminDao;
    /**
     * 管理员登录
     * @param name
     * @param password
     * @param request
     * @return
     */
    @Override
    public ResultMsg login(String name, String password, HttpServletRequest request) {
        QueryWrapper<TbAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_name",name);
        TbAdmin tbAdmin = this.getOne(wrapper);

        if(tbAdmin==null){
            return ResultMsg.faild(250, "管理员不存在");
        }
        if(!(tbAdmin.getAdminPass().equals(password))){
            return ResultMsg.faild(251,"用户名密码不匹配");
        }
        String adminId = String.valueOf(tbAdmin.getAdminId());
        String jwt = TokenUtils.create(adminId, tbAdmin.getAdminPass());
        return ResultMsg.success(jwt);
    }

    /**
     * 根据管理员昵称查询管理员信息
     * @param name
     * @return
     */
    @Override
    public ResultMsg findByName(String name) {
        QueryWrapper<TbAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_name",name);
        TbAdmin tbAdmin = this.getOne(wrapper);
        if(tbAdmin!=null){
            return ResultMsg.success(tbAdmin);
        }
        return null;
    }

    /**
     *修改管理员信息
     * @param tbAdmin
     * @return
     */
    @Override
    public ResultMsg updateAdmin(TbAdmin tbAdmin) {
        this.saveOrUpdate(tbAdmin);
        return ResultMsg.success();
    }

    /**
     * 修改密码
     * @param
     * @return
     */
    @Override
    public ResultMsg setPass(int adminId, String oldPass, String newPass, String rePass) {
        TbAdmin tbAdmin = this.getById(adminId);
        //判断旧密码是否正确
        if(!(tbAdmin.getAdminPass().equals(oldPass))){
            return ResultMsg.faild(252,"原密码输入错误");
        }
        //判断两次输入的是否一致
        if(!(newPass.equals(rePass))){
            return ResultMsg.faild(253,"两次输入不一致");
        }
        //判断新密码是否与旧密码一致
        if(newPass.equals(oldPass)){
            return ResultMsg.faild(254,"亲，新密码不能和旧密码一样哦！！！");
        }
        //修改密码
        if(newPass!=null){
            adminDao.updatePass(adminId,newPass);
        }
        return ResultMsg.success();
    }
}
